package com.OjSystem.job.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.OjSystem.common.redis.Constants.RedisConstants;
import com.OjSystem.common.redis.service.RedisService;
import com.OjSystem.job.domain.Exam;
import com.OjSystem.job.mapper.ExamMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class ExamXxlJob {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @XxlJob("examListOrganizeHandler")
    public void examListOrganizeHandler() {
        log.info("examListOrganizeHandler执行成功！！！");

        //未完赛竞赛列表
        List<Exam> unFinishList = examMapper.selectList(new
                LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime,
                        Exam::getEndTime)
                .gt(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, 1)
                .orderByDesc(Exam::getCreateTime));
        refreshCache(unFinishList, RedisConstants.EXAM_UNFINISHED_LIST);

        //历史竞赛列表
        List<Exam> historyExamList = examMapper.selectList(new
                LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime,
                        Exam::getEndTime)
                .le(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, 1)
                .orderByDesc(Exam::getCreateTime));
        refreshCache(historyExamList, RedisConstants.EXAM_HISTORY_LIST);
    }

    public void refreshCache(List<Exam> examList, String examListKey) {
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }
        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap); //刷新详情缓存
        redisService.deleteObject(examListKey);
        redisService.rightPushAll(examListKey, examIdList); //刷新列表缓存
    }

    private String getDetailKey(Long examId) {
        return RedisConstants.EXAM_DETAIL + examId;
    }
}
